import { login, getUserInfo, getUserPhoto } from '@/api/user'
import { getToken, removeToken, setTimeStamp, setToken } from '@/utils/auth'

export default {
  // 开启命名空间，不要和其他模块产生影响
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      // 将token赋值给state中的token
      state.token = token
      // 存储token
      setToken(token)
    },
    removeToken(state) {
      // 删除token
      state.token = null
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async updateToken(context, data) {
      const token = await login(data)
      console.log(token)
      context.commit('setToken', token)
      // 设置时间戳
      setTimeStamp()
    },
    async getUserInfo(context) {
      const userInfo = await getUserInfo()
      console.log(userInfo)
      // context.commit('setUserInfo', userInfo)
      const staffPhoto = await getUserPhoto(userInfo.userId)
      console.log(staffPhoto)
      const baseInfo = {
        ...userInfo,
        ...staffPhoto
      }
      context.commit('setUserInfo', baseInfo)
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  },
  modules: {}
}
